package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author: atguigu
 * @create: 2024-05-09 10:46
 */
@Slf4j
@Aspect
@Component
public class GuiGuLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 环绕通知 对所有业务服务模块从api包下 使用@GuiGuLogin注解方法进行增强，从请求中获取请求头token，查询用户信息，校验，将用户ID存入ThreadLocal
     *
     * @param pjp        目标方法对象
     * @param guiGuLogin 作用在方法上自定义注解对象 获取到注解中属性值
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(guiGuLogin)")
    public Object doBasicProfiling(ProceedingJoinPoint pjp, GuiGuLogin guiGuLogin) throws Throwable {
        log.info("[认证切面]前置逻辑...");
        //1.获取请求头token中用户访问令牌
        //1.1 获取请求对象 RequestAttributes:接口 ServletRequestAttributes：实现类(封装请求响应对象)
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = sra.getRequest();
        //1.2 获取请求头：token
        String token = request.getHeader("token");

        //2.根据令牌获取存入到redis中用户信息（当初登录存入Redis中key=user:login:token Value=UserInfoVo）
        //2.1 构建查询用户信息key
        String key = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        //2.2 获取存在redis中用户基本信息(UserInfoVo)
        UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(key);

        //3.判断目标方法是否需要登录
        if (guiGuLogin.required() && userInfoVo == null) {
            //抛出异常208业务状态码，前端提醒用户登录，引导用户到登录页面
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        //4.将用户ID存入ThreadLocal
        if (userInfoVo != null) {
            AuthContextHolder.setUserId(userInfoVo.getId());
        }
        //5.执行目标方法时候，如果用户登录将用户ID存入ThreadLocal，自然在目标方法（controller，service,mapper）从ThreadLocal获取用户ID
        Object retVal = pjp.proceed();

        log.info("[认证切面]后置逻辑...");
        //6.清理ThreadLocal
        AuthContextHolder.removeUserId();
        return retVal;
    }
}
